/*
 *
 * @Author: ljb
 * @Date: 2018-09-18 08:54:03
 * @Last Modified by: ljb
 * @Last Modified time: 2019-01-29 14:43:32
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
	@deep: ~'>>>';
	/*@link https://github.com/less/less.js/issues/2623 */
	.v-customer-share-product-views{
		padding: 0 5px 5px 5px;
		background-color: #f0f0f0;
		overflow: auto;
		.card {
			background-color: #fff;
			border-radius:8px;
		}
		.header {
			padding: 30px;
			h2 {
				font-weight: 400;
				font-size: 18px;
				color: #666;
				.main__title {
					color: #333;
				}
				.sub__title {
					font-size: 16px;
				}
			}
			.search-form {
				margin-top: 20px;
				.search-label {
					font-size: 16px;
					color: #333;
					&.top-deviation {
						margin-top: 2px;
					}
				}
				.search-item {
					margin-bottom: 20px;
					&:last-of-type {
						margin-bottom: 0;
					}
				}
				/*修改排序按钮的位置*/
				.sort-btn {
					margin-left: 25px;
					&:last-of-type {
						margin-left: 50px;
					}
				}
				/*修改排序按钮的位置 END*/
				/* @{deep}的作用为影响组件内的样式，vue-loader 12.2版本之后可用 @link https://mp.weixin.qq.com/s/qjUvLSIfjIDQId3rNtNMYw */
				@{deep} .ivu-form-item-label {
					font-size: 14px;
				}
				@{deep} .ivu-form-item {
					margin-bottom: 0;
				}
			}
		}
		.content {
			padding: 20px 30px;
			margin-top: 10px;
			.products{
				overflow: hidden;
			}
			.products__list{
				list-style: none;
				font-size: 0;
				margin: 0 -1%;
				padding: 5px 5px 0;
			}
			.products__list__item{
				width: 18%;
				margin:0 1% 30px;
				min-width: 210px;
				display: inline-block;
				transition: box-shadow .3s 0s ease;
				border: 1px solid #e5e5e5;
				&:hover {
					border-color: transparent;
					box-shadow: 0px 0px 15px rgba(0,0,0,0.1);
				}
			}
			.no-products {
				width: 100%;
				padding: 117px 0 160px;
				margin: 0 auto;
				text-align: center;
				img {
					width: 250px;
				}
				p {
					margin-top: 20px;
					font-size: 24px;
					font-weight: 400;
					color: #87C0FF;
				}
			}
		}

	}

</style>
<template>
	<div class="v-customer-share-product-views no-scrollbar">
		<!-- 头部部分 -->
		<div class="header card">
			<!-- 选项卡选中展示的面包屑 -->
			<h2>
				<span class="main__title">{{ $t('menus.share_product') }}</span>
				<span>/</span>
				<span class="sub__title">{{ tab_name_map[query_info.product_type] }}</span>
			</h2>
			<!-- 搜索部分 -->
			<div class="search-form">
				<Row
					type="flex"
					align="middle"
					class="search-item">
					<i-col
						span="1"
						class="search-label">{{ $t('common.search') + $t('common.colon') }}</i-col>
					<i-col span="22">
						<Form
							ref="formInline"
							inline
							@keydown.native.enter.prevent="confirmSearch">
							<Form-item
								:label-width="80"
								:label="$t('common.keyword')"
								prop="keyword">
								<i-input
									v-model="query_info.keyword"
									:placeholder="$t('common.placeholder',{field: $t('common.keyword')})"
									type="text"/>
							</Form-item>
							<Form-item>
								<Button
									type="primary"
									@click="confirmSearch">
									{{ $t('common.search') }}
								</Button>
							</Form-item>
						</Form>
					</i-col>
				</Row>
				<Row
					v-if="productCategory && productCategory.length > 0"
					type="flex"
					align="top"
					class="search-item">
					<i-col
						:span="label_span"
						class="search-label top-deviation">{{ $t('product.category') + $t('common.colon') }}</i-col>
					<i-col :span="23 - label_span">
						<itemGroup
							v-model="query_info.category_id"
							:lists="productCategory"
							name="category"
							@search="confirmSearch"/>
					</i-col>
				</Row>
				<Row
					v-if="productBrands && productBrands.length > 0"
					type="flex"
					align="top"
					class="search-item">
					<i-col
						span="1"
						class="search-label top-deviation">{{ $t('product.brand') + $t('common.colon') }}</i-col>
					<i-col span="22">
						<itemGroup
							v-model="query_info.brand_name"
							:lists="productBrands"
							need-key="name"
							name="brand"
							@search="confirmSearch"/>
					</i-col>
				</Row>
				<Row
					type="flex"
					align="middle"
					class="search-item">
					<i-col
						span="1"
						class="search-label">{{ $t('common.sort') + $t('common.colon') }}</i-col>
					<i-col span="22">
						<sortBtn
							ref="ref_count"
							:name="$t('share_product.quote')"
							param-key="ref_count"
							class="sort-btn"
							@sort="sortList"/>
						<sortBtn
							ref="created_at"
							:name="$t('share_product.new_upload')"
							param-key="created_at"
							class="sort-btn"
							@sort="sortList"/>
					</i-col>
				</Row>
			</div>
		</div>

		<!-- 产品列表 -->
		<div class="content card">
			<Tabs
				v-model="query_info.product_type"
				type="card"
				@on-click="changeTab">

				<TabPane
					:label="$t('share_product.cosmetics')"
					name="1">
					<div
						v-show="query_info.product_type === '1'"
						class="products">
						<div v-if="productData.length > 0">
							<ul
								class="products__list">
								<li
									v-for="product in productData"
									:key="product.id"
									class="products__list__item"
									@click="showDetail(product)">
									<productCard
										:count="product.ref_count"
										:image="product.thumb_url"
										:title="product.title"
										:selected="parseInt(product.customer_ref_count, 10) > 0"/>
								</li>
							</ul>

							<!-- 分页组件 -->
							<Row
								type="flex"
								justify="center">
								<Page
									:total="cosmetics_products.total"
									:current="cosmetics_products.current_page"
									:page-size="query_info.per_page"
									placement="top"
									show-sizer
									show-total
									@on-change="pageChange"
									@on-page-size-change="perPageChange"/>
							</Row>
						</div>

						<div
							v-else
							class="no-products">
							<img
								:src="no_product_img"
								alt="">
							<p>{{ $t('share_product.no_product_tip') }}</p>
						</div>

					</div>
				</TabPane>

				<TabPane
					:label="$t('share_product.skin_care_products')"
					name="0">
					<div
						v-show="query_info.product_type === '0'"
						class="products">
						<div v-if="productData.length > 0">
							<ul
								class="products__list">
								<li
									v-for="product in productData"
									:key="product.id"
									class="products__list__item"
									@click="showDetail(product)">
									<productCard
										:count="product.ref_count"
										:image="product.thumb_url"
										:title="product.title"
										:selected="parseInt(product.customer_ref_count, 10) > 0"/>
								</li>
							</ul>
							<!-- 分页组件 -->
							<Row
								type="flex"
								justify="center">
								<Page
									:total="skin_care_products.total"
									:current="skin_care_products.current_page"
									:page-size="query_info.per_page"
									placement="top"
									show-sizer
									show-total
									@on-change="pageChange"
									@on-page-size-change="perPageChange"/>
							</Row>
						</div>
						<div
							v-else
							class="no-products">
							<img
								:src="no_product_img"
								alt="">
							<p>{{ $t('share_product.no_product_tip') }}</p>
						</div>
					</div>
				</TabPane>
			</Tabs>
		</div>

		<Spin
			v-if="tab_loading"
			size="large"
			fix/>

		<Modal
			v-model="show_detail_modal"
			:title="$t('share_product.product_detail')"
			width="1200"
			class-name="vertical-middle-modal no-footer-modal personal-header"
			@on-visible-change="handleVisibleChange">
			<i slot="footer"/>
			<component
				:is="component_map[query_info.product_type]"
				:product-detail="product_detail"
				:customer-brands="customer_brands"
				@add="addToProduct"/>
		</Modal>

		<Modal
			v-model="show_success_message"
			class-name="vertical-middle-modal no-footer-modal"
			width="1200">
			<i slot="footer"/>
			<successMessage @confirm="toProduct"/>
		</Modal>
	</div>
</template>

<script>

import API_LIST from 'src/API_LIST';

import { mapMutations, mapGetters } from 'vuex';

import itemGroup from 'src/views/component/item-group';
import sortBtn from 'src/views/component/sort-btn';

import qs from 'qs';
import { deleteEmptyValue } from 'src/utils/utils';	// 处理空参数

import productCard from './product-card';
import careProdcutDetail from './care-product-detail';
import makeupProdcutDetail from './makeup-product-detail';
import successMessage from './success-message';

// TabPane里面的name值1代表化妆品，0代表护肤品

export default {
	name: 'ShareProductViews',
	components: {
		itemGroup,
		sortBtn,
		productCard,
		makeupProdcutDetail,
		careProdcutDetail,
		successMessage,
	},
	data() {
		return {
			label_span: 1,

			no_product_img: require('src/assets/img/shuju_wushuju_icon.svg'),

			query_info: {
				page: 1,

				per_page: 20,

				keyword: '',

				brand_name: '',

				category_id: 0,

				product_type: '1',

				order_column: '',

				sort: '',
			},

			search_info: {
				page: 1,

				per_page: 20,
			}, // 分页信息

			tab_loading: false,	// 请求产品列表时的loading

			group_categories: [],	// 产品分类组

			brands: [],	// 产品品牌

			cosmetics_products: {},	// 化妆品

			skin_care_products: {},	// 护肤品

			tab_name_map: {
				0: this.$t('share_product.skin_care_products'),
				1: this.$t('share_product.cosmetics'),
			},

			product_map: {
				0: 'skin_care_products',
				1: 'cosmetics_products',
			},

			component_map: {
				0: 'careProdcutDetail',
				1: 'makeupProdcutDetail',
			},

			show_detail_modal: false,	// 详情模态框显隐控制

			show_success_message: false,	// 成功提示框的显隐

			product_detail: {},		// 商品详情

			customer_brands: [],

		};
	},
	computed: {
		...mapGetters('app', [
			'getCurrentLanguage',
		]),
		// 返回产品分类
		productCategory() {
			const categories = this.group_categories;
			const type = this.query_info.product_type;
			const current_category = categories.filter(category => parseInt(category.custom_type_id, 10) === parseInt(type, 10))[0];
			return current_category ? current_category.categories : [];
		},
		// 返回产品品牌
		productBrands() {
			const categories = this.productCategory;
			const { category_id } = this.query_info;
			const [current_brands] = categories.filter(category => String(category.id) === String(category_id));
			return current_brands ? current_brands.brands : [];
		},
		// 产品数据
		productData() {
			const product_key = this.product_map[this.query_info.product_type];
			return this[product_key].data || [];
		},
	},
	watch: {
		'query_info.category_id': {
			handler() {
				this.confirmSearch();
			},
		},
		'query_info.brand_name': {
			handler() {
				this.confirmSearch();
			},
		},
	},
	created() {
		this.fetchProductInfo();
	},
	mounted() {
		if (this.getCurrentLanguage === 'English') {
			this.label_span = 2;
		}

		this.fetchProductList(this.query_info);
	},
	methods: {
		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 跳转产品管理
		 * @return {undefined}
		 */
		toProduct() {
			this.show_success_message = false;
			this.$router.push({
				path: '/customer/product',
				query: {
					watch: true,
				},
			});
		},

		/**
		 * 显示商品详情
		 * @param  {Object} detail {商品详情对象}
		 * @return {undefined}
		 */
		showDetail(detail) {
			this.product_detail = detail;
			this.show_detail_modal = true;
		},

		/**
         * 切换tab
         * @param  {String} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			this.resetParam();

			switch (tab_name) {
			case '0':

				this.cosmetics_products.data = [];

				break;

			default:

				this.skin_care_products.data = [];

				break;
			}
			this.confirmSearch();
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchProductList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchProductList(this.query_info);
		},

		/**
		 * 重置搜索参数
		 * @return {undefined}
		 */
		resetParam() {
			this.query_info.page = 1;
			this.query_info.per_page = 20;
			this.query_info.keyword = '';
			this.query_info.brand_name = '';
			this.query_info.category_id = '';
			this.query_info.sort = '';
			this.query_info.order_column = '';
			this.$refs.ref_count.reset();
			this.$refs.created_at.reset();
		},

		/**
		 * 排序的方法
		 * @param  {String} key   {排序的字段}
		 * @param  {String} value {排序的值，正序ASC或者倒序DESC}
		 * @return {undefined}
		 */
		sortList({ key, value }) {
			if (this.query_info.order_column && this.query_info.order_column !== key) {
				this.$refs[this.query_info.order_column].reset();
			}

			this.query_info.order_column = value ? key : '';
			this.query_info.sort = value;

			this.confirmSearch();
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch() {
			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.fetchProductList(this.query_info);
		},

		/**
		 * 添加到商品管理的post方法
		 * @param  {Object} param {需要提交的参数对象}
		 * @return {undefined}
		 */
		addToProduct(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.show_detail_modal = false;

			this.$http.post(API_LIST.CUST_SHARE_PRODUCT, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.show_success_message = true;

					this.fetchProductList(this.search_info);

					this.fetchProductInfo();
				})
				.catch((err) => {
					this.$Message.error(err.message);
					this.show_detail_modal = true;
				})
				.then(this.closeSpin);
		},

		/**
		 * 获取产品品牌，分类等商品信息
		 * @return {undefined}
		 */
		fetchProductInfo() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.get(`${API_LIST.CUST_SHARE_PRODUCT}/create`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.brands = data.brands;

					this.group_categories = data.group_categories;

					this.customer_brands = data.customer_brands_with_series || [];
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
		 * 请求共享产品列表
		 * @param  {Object} param {请求的参数对象}
		 * @return {undefined}
		 */
		fetchProductList(param) {
			this.tab_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.CUST_SHARE_PRODUCT}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					const product_key = this.product_map[this.query_info.product_type];

					this[product_key] = data.products;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.tab_loading = false; });
		},

		/**
		 * 模态框关闭时清空数据
		 * @param {Boolean} is_visible
		 */
		handleVisibleChange(is_visible) {
			if (!is_visible) {
				this.product_detail = {};
			}
		},
	},
};
</script>
